package com.firexxx.vp.domain.audio;

import com.firexxx.common.domain.AbstractEntity;
import com.firexxx.common.errors.BaseErrors;
import com.firexxx.vp.domain.stb.StbKey;
import lombok.AccessLevel;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.Where;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.io.IOException;

/**
 * @description: TODO
 * @throws:
 * @author: zhuangzhang2
 * @date: 2019/12/18 17:08
 */
@Entity
@Table(name = "audio")
@DynamicInsert
@DynamicUpdate
@Where(clause = "is_deleted = false")
@Data
@NoArgsConstructor(access = AccessLevel.PACKAGE)
@Slf4j
public class AudioEntity extends AbstractEntity {

    @NotNull
    @Embedded
    @Setter
    private StbKey stbKey;

    @NotNull
    @Column(name = "audio_id")
    private String audioId;

    @NotNull
    @Enumerated(EnumType.STRING)
    @Column(name = "audio_type")
    private AudioType audioType;

    @NotNull
    @Embedded
    private AudioStorage audioStorage;

    @Transient
    private byte[] pcmContent;

    public AudioEntity(@NotNull StbKey stbKey, @NotNull String audioId, @NotNull AudioType audioType, @NotNull byte[] content) {
        this.stbKey = stbKey;
        this.audioId = audioId;
        this.audioType = audioType;
        this.audioStorage = AudioStorage.cloneDefaultAudioStorage();
        if (audioType == AudioType.PCM) {
            this.pcmContent = content;
        }
    }

    public byte[] getContent() {
        if (pcmContent == null) {
            load();
        }

        byte[] content = null;
        //1、从数据库加载的或者controller加载的音频格式为pcm，必然pcmContent不为空
        if (pcmContent != null) {
            content = pcmContent;
        }

        if (audioType == AudioType.PCM) {
            BaseErrors.AUDIO_ERROR.ifThrow(
                    content == null,
                    "获取pcm音频内容异常"
            );
        }

        return content;
    }

    private byte[] load() {
        if (audioStorage == null) {
            audioStorage = AudioStorage.cloneDefaultAudioStorage();
        }

        if (this.audioType == AudioType.PCM) {
            byte[] content = audioStorage.load(stbKey.getChannelId(),
                    stbKey.getUniqueKey(), audioId + ".pcm");
            pcmContent = content;
        } else {
            BaseErrors.AUDIO_ERROR.doThrow(
                    "获取pcm音频内容异常"
            );
        }

        return pcmContent;
    }

    public void store() throws IOException {
        if (audioStorage == null) {
            audioStorage = AudioStorage.cloneDefaultAudioStorage();
        }

        if (this.audioType == AudioType.PCM) {
            audioStorage.store(stbKey.getChannelId(), stbKey.getUniqueKey(),
                    audioId + ".pcm", pcmContent);
        }
    }
}